package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.dto.ProductSkuVo;
import com.spzx.product.vo.SkuPriceVo;
import com.spzx.product.query.SkuQuery;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
@RequiredArgsConstructor
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {
    private RedisTemplate redisTemplate;
    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        ProductSku productSku = baseMapper.selectById(skuId);
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long productId) {
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, productId);
        List<ProductSku> productSkus = baseMapper.selectList(wrapper);
        HashMap<String, Long> result = new HashMap<>();
        productSkus.forEach(productSku->{
           result.put(productSku.getSkuSpec(), productSku.getId());
        });
        return result;
    }

    @Override
    public ProductSku getProductSku(Long skuId) {
        //1.sku value key：product：sku：skuId, 尝试查询缓存
        String skuKey = getSkuKey(skuId);
        ProductSku productSku = null;
        try {
            productSku = (ProductSku) redisTemplate.opsForValue().get(skuKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(productSku !=null){
            return productSku; //也是我们自旋的退出条件,如果缓存宕机了，就会一直自旋，所以上面捕捉异常。
        }else{
            //2 .如果查询不到就去查数据库，并更新缓存（构建分布式锁key：lock：product：sku：skuId ； ）
            String lockKey = getLock(skuId);
            String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
            Boolean hasLock = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
            if(hasLock){
                //3.如果成功获取锁，查询数据库，更新缓存，释放锁
                try {
                    //查询缓存，上一个释放锁的人缓存可能更新完毕了
                     productSku =(ProductSku) redisTemplate.opsForValue().get(skuKey);
                    if(productSku !=null) {
                        return productSku;
                    }
                    //这里我们已经保证目标商品不为空了（位图）
                    productSku = this.getById(skuId);
                    redisTemplate.opsForValue().setIfAbsent(skuKey, productSku,7,TimeUnit.DAYS);
                    return productSku;
                }finally {
                    //4.业务执行完毕释放锁
                    String scriptText = """
                    if redis.call('get',KEYS[1]) == ARGV[1]
                    then
                        return redis.call('del',KEYS[1])
                    else
                        return 0
                    end
                    """;
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(scriptText);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey), lockValue);
                }
            }else{
                //4.获取锁失败，自旋
                return getProductSku(skuId);
            }
        }

    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkuList = baseMapper.selectList(
                new LambdaQueryWrapper<ProductSku>()
                        .in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice)
        );
        List<SkuPriceVo> skuPriceVos = productSkuList.stream().map(item -> {
            SkuPriceVo skuPrice = new SkuPriceVo();
            skuPrice.setSkuId(item.getId());
            skuPrice.setSalePrice(item.getSalePrice());
            return skuPrice;
        }).collect(Collectors.toList());
        return skuPriceVos;
    }

    public String getSkuKey(Long skuId){
        return "product:sku:"+skuId;
    }
    public String getLock(Long skuId){
        return "lock:product:sku:"+skuId;
    }
}
